﻿
var serializer = new JSONSerializer();

$(document).ready(function () {

    //待匹配理财收益ID
    var url = new Url();
    var $Id = url.GetQueryString("id");

    $.ajax({
        type: "post",
        url: '../Handler/FinaProfitHandler.ashx',
        dataType: "json",
        data: { Id: $Id, Type: 1, _: Math.random() },
        async: false,
        cache: false,
        complete: function () {
        },
        success: function (result) {
            if (result.Status) {
                serializer.DeSerializeToSpan($("#showResult"), result.Data);

                //预加载债权匹配信息列表
                $.ajax({
                    type: "post",
                    url: "../Handler/CreditProfitMatchHandler.ashx",
                    dataType: "json",
                    data: { FinaProfitId: $("div[data-name='FinaProfitId']").text(), type: 0, _: Math.random() },
                    async: true,
                    cache: false,
                    complete: function () {
                    },
                    success: function (result) {
                        if (result.Status) {
                            var $Total = 0;
                            $.each(result.Data, function (index, item) {
                                $Total += parseFloat(item.LoanMatchAmount);
                                $("#MatchCreditTemplete").tmpl(item).insertBefore($("#rowMatchAmountTotal"));
                            });
                            $("#totalMatchAmount").text($Total.toFixed(2));
                        }
                    }
                });


                //单独绑定理财规模*10000
                $("div[data-name='Amount']").text(result.Data.Amount * 10000);
                $("#animation").hide();
                $("#showResult").show();
            }
        }
    });


    //异步加载借款产品
    $("#btnCreditMatch").one("click", function () {
        $.ajax({
            type: "post",
            url: "../Handler/ProductHandler.ashx",
            dataType: "json",
            data: { ProductType: 2, type: 0, _: Math.random() },
            async: false,
            cache: false,
            complete: function () {
            },
            success: function (result) {
                var stropt = '<option value="-1">请选择</option>';
                $.each(result, function (index, item) {
                    stropt += "<option value=" + item.ProductId + ">" + item.ProductName + "</option>";
                });
                $('select[name=ProductTypeId]').html(stropt);
            }
        });
    });

    //债权匹配弹出借款列表
    $(".btnSearchBorrow").click(function () {
        $(".tblCreditMatch").html("");
        var filter = new JSONSerializer().Serialize("#searchArea");
        filter._ = Math.random();
        filter.Type = 26;
        filter.FinaOrderId = $("[data-name='FinaId']").text();
        $.ajax({
            type: "post",
            url: "../Handler/LoanProductOrderHandler.ashx",
            dataType: "json",
            data: filter,
            async: false,
            cache: false,
            complete: function () {
            },
            success: function (result) {
                if (result.Status) {
                    $.each(result.Data, function (index, item) {
                        $("#WaitMatchCreditTemplete").tmpl(item).appendTo($(".tblCreditMatch"));
                    })
                }
                else {
                    alert(result.Message);
                }
            }
        });
    });

    //是否全债权匹配信息
    $("#chkMatchAll").click(function () {
        var matchChecked = $(this).is(":checked");
        if (matchChecked) {
            $("[name=chkMatch]:checkbox").prop("checked", true);
        }
        else {
            $("[name=chkMatch]:checkbox").prop("checked", false);
        }
    });


    //选择借款订单进行匹配
    $("#btnMatch").click(function () {
        $("[name=chkMatch]:checkbox").each(function (i) {
            if ($(this).is(":checked")) {
                var $rowChecked = $(this).closest('.rowMatch');
                var array = new Array();
                $rowChecked.find("[data-name]:not('.NonSerialized')").each(function (index) {
                    array.push('"' + $(this).attr("data-name") + '":"' + $(this).text() + '"');
                });
                var item = $.parseJSON("{" + array.join(",") + "}");
                //订单已经在借款记录表中存在
                var flag = false;
                $(".tblBorrowRecord  .rowBorrowRecord").each(function (i) {
                    if ($(this).attr("data-OrderId") == item.LoanOrderId) {
                        flag = true;
                        return false;
                    }
                });
                if (!flag) {
                    $("#MatchCreditTemplete").tmpl(item).insertBefore($("#rowMatchAmountTotal"));
                }
            }
        });
        //隐藏债权匹配模态框
        $(".close").click();
    });

    //匹配金额总计
    $(".tblBorrowRecord").on("change", "input.txtMatchAmount", function () {
        var waitAmount = parseFloat($(this).closest('td').prev().text());
        var matchAmount = parseFloat($(this).val());
        if (waitAmount < matchAmount) {
            alert("匹配金额不能大于可匹配金额!");
            $(this).val(waitAmount);
        }
        var $Total = 0;
        $(".txtMatchAmount").each(function (i) {
            $Total += parseFloat($(this).val());
        });
        if (isNaN($Total)) {
            $("#totalMatchAmount").text("");
        }
        else {
            $("#totalMatchAmount").text($Total.toFixed(2));
        }
    });

    //是否全选借款人记录信息
    $("#chkRecordAll").click(function () {
        var matchChecked = $(this).is(":checked");
        if (matchChecked) {
            $("[name=chkRecord]:checkbox").prop("checked", true);
        }
        else {
            $("[name=chkRecord]:checkbox").prop("checked", false);
        }
    });

    //借款人记录删除
    $("#btnDeleteRecord").click(function () {

        $("#chkRecordAll").prop("checked", false);
        $("[name=chkRecord]:checkbox").each(function (i) {
            if ($(this).is(":checked")) {
                $(this).closest('.rowBorrowRecord').remove();;
            }
        });
        if ($(".tblBorrowRecord .rowBorrowRecord").length == 0) {
            $("#totalMatchAmount").text("");
        }
        $("tr.rowBorrowRecord").change();
    });

    //借款订单自动匹配
    $("#btnAutoMatch").click(function () {

        var minMatchAmount = parseFloat($(":input[name='MinMatchAmount']").val());
        var maxMatchAmount = parseFloat($(":input[name='MaxMatchAmount']").val());
        if (isNaN(minMatchAmount) || isNaN(maxMatchAmount)) {
            alert("请输入合法的匹配范围！");
            return false;
        }
        //匹配金额上限，也就是理财订单的理财规模
        var topLimitAmount = parseFloat($('span[data-name="Profit"]').text());
        //已完成匹配金额
        var completeAmount = parseFloat($("#totalMatchAmount").text());
        if (isNaN(completeAmount)) {
            completeAmount = parseFloat(0);
        }
        //遍历搜索查询得到的借款订单编号
        $('tr.rowMatch').each(function (index, val) {
            var remainAmount = parseFloat($(this).find("[data-name='RemainMatchAmount']").text());
            if (remainAmount > minMatchAmount) {
                if (completeAmount >= topLimitAmount) {
                    return false;
                }
                var array = new Array();
                $(this).find("[data-name]:not('.NonSerialized')").each(function (index) {
                    array.push('"' + $(this).attr("data-name") + '":"' + $(this).text() + '"');
                });
                var item = $.parseJSON("{" + array.join(",") + "}");
                var flag = false;
                $(".tblBorrowRecord  .rowBorrowRecord").each(function (i) {
                    if ($(this).attr("data-OrderId") == item.LoanOrderId) {
                        flag = true;
                        return false;
                    }
                });
                if (!flag) {
                    var randomAmount;
                    if (remainAmount < maxMatchAmount) {
                        randomAmount = Math.random() * (remainAmount - minMatchAmount + 1) + minMatchAmount;
                    }
                    else {
                        randomAmount = Math.random() * (maxMatchAmount - minMatchAmount + 1) + minMatchAmount;
                    }
                    item.LoanMatchAmount = randomAmount = parseFloat(randomAmount).toFixed(2);
                    if (topLimitAmount - completeAmount < randomAmount) {
                        item.LoanMatchAmount = parseFloat(topLimitAmount - completeAmount).toFixed(2);
                    }
                    $("#MatchCreditTemplete").tmpl(item).insertBefore($("#rowMatchAmountTotal"));
                    completeAmount = (parseFloat(completeAmount) + parseFloat(item.LoanMatchAmount)).toFixed(2);
                }

            }
        });
        //计算总计
        $("input.txtMatchAmount").change();
        //隐藏债权匹配模态框
        $(".close").click();

    });

    //保存债权匹配信息
    $("#btnSaveCreditMatch").click(function () {
        //每条债权匹配信息的匹配金额不能是非数字
        var flag = true;
        $(".tblBorrowRecord  tr.rowBorrowRecord").each(function () {
            var amount = parseFloat($(this).find("input[name=MatchAmount]").val());
            if (isNaN(amount)) {
                flag = false;
                return false;
            }
        });
        if (!flag) {
            alert("请您检查输入的匹配金额是否为正确的金额！");
            return false;
        }

        var finaProfitId = $("div[data-name='FinaProfitId']").text();
        var profitMatchAmount = $("span[data-name='Profit']").text();//本期债权收益
        var listProfitMatch = new Array();
        $(".tblBorrowRecord  tr.rowBorrowRecord").each(function () {
            var item = new Object();
            item.FinaProfitId = finaProfitId;
            item.ProfitMatchAmount = profitMatchAmount;
            item.LoanOrderId = $(this).find("[data-name=OrderId]").text();
            item.LoanMatchAmount = $(this).find("input[name=MatchAmount]").val();
            listProfitMatch.push(item);
        });
        $.ajax({
            type: 'post',
            url: '../Handler/CreditProfitMatchHandler.ashx',
            dataType: 'json',
            data: { Type: 1, FinaProfitId: $("div[data-name='FinaProfitId']").text(), ProfitMatchInfo: JSON.stringify(listProfitMatch), _: Math.random() },
            async: false,
            cache: false,
            complete: function () {
            },
            success: function (result) {
                alert(result.Message);
            }
        });
    });

    var checkSubmitFlg = false;
    //提交既有债权匹配信息
    $("#btnSubmitCreditMatch").click(function () {
        if (!checkSubmitFlg) {// 第一次提交
            checkSubmitFlg = true;
        } else {//重复提交
            return false;
        }
        //每条债权匹配信息的匹配金额不能是非数字
        var flag = true;
        $(".tblBorrowRecord  tr.rowBorrowRecord").each(function () {
            var amount = parseFloat($(this).find("input[name=MatchAmount]").val());
            if (isNaN(amount)) {
                flag = false;
                return false;
            }
        });
        if (!flag) {
            alert("请您检查输入的匹配金额是否为正确的数字格式！");
            checkSubmitFlg = false;
            return false;
        }

        //匹配金额上限，也就是本期债权收益的金额
        var topLimitAmount = parseFloat($("span[data-name='Profit']").text());//本期债权收益
        //已完成匹配金额
        var completeAmount = parseFloat($("#totalMatchAmount").text());
        if (isNaN(completeAmount) || topLimitAmount != completeAmount) {
            alert("匹配金额总计不等于本期债权收益，不能提交！");
            checkSubmitFlg = false;
            return false;
        }

        var finaProfitId = $("div[data-name='FinaProfitId']").text();
        var listProfitMatch = new Array();
        $(".tblBorrowRecord  tr.rowBorrowRecord").each(function () {
            var item = new Object();
            item.FinaProfitId = finaProfitId;
            item.ProfitMatchAmount = topLimitAmount;
            item.LoanOrderId = $(this).find("[data-name=OrderId]").text();
            item.LoanMatchAmount = $(this).find("input[name=MatchAmount]").val();
            listProfitMatch.push(item);
        });
        $.ajax({
            type: 'post',
            url: '../Handler/CreditProfitMatchHandler.ashx',
            dataType: 'json',
            data: { Type: 2, FinaProfitId: $("div[data-name='FinaProfitId']").text(), ProfitMatchInfo: JSON.stringify(listProfitMatch), _: Math.random() },
            async: false,
            cache: false,
            complete: function () {
                checkSubmitFlg = false;
                iscommit = true;
            },
            success: function (result) {
                alert(result.Message);
                iscommit = true;
                checkSubmitFlg = false;
                if (result.Status) {
                    location.href = "AchieveMatchExsitCredit.aspx?css=3062";
                }
            }
        });
    });
});